<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Channel;
use App\Utils\UploadHelper;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class UserImportController extends Controller
{
    public function getChannels()
    {
        return Channel::query()->select('id', 'name')->where('agent_id', request()->agent_id)->get();
    }

    public function excelimport()
    {
        $isFile = request()->hasFile('file');
        if (!$isFile) {
            throw new \Exception('请上传文件');
        }

        $data = UploadHelper::readExcel(request()->file('file'));
        unset($data[0]);

        return $data;
    }

    public function userimport(Request $request)
    {
        set_time_limit(0);
        $agent_id = request()->agent_id;

        $channel_id = request()->channel_id ?? 0;

        $file_data = json_decode(request()->file_data, true);

        $save_data = [];

        foreach ($file_data as $k => $v) {
            $tmp = [
                'mobile' => $v[0],
                'password' => '',
                'wallet_address' => '',
                'agent_id' => $agent_id,
                'parent_id' => 0,
                'channel_id' => $channel_id,
            ];

            $save_data[] = $tmp;
        }

        DB::table('frontend_users')->insert($save_data);
    }
}
